package gg.com.toolbox.activity;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import gg.com.toolbox.R;
import gg.com.toolbox.adapter.FunctionAdapter;
import gg.com.toolbox.service.LoginService;
import gg.com.toolbox.tools.BaseActivity;
import gg.com.toolbox.util.AppConstant;
import gg.com.toolbox.util.DateUtils;
import gg.com.toolbox.util.MyApplication;

/**
 * 主页
 * Created by gaoge on 2017/10/10.
 */

public class MainActivity extends BaseActivity implements AdapterView.OnItemClickListener {

    //数据显示
    private GridView gridview = null;
    //适配器
    private FunctionAdapter functionAdapter = null;
    //保存功能的集合
    private ArrayList<HashMap<String, String>> functionList = null;
    //动作对象
    private Intent intent = null;
    //服务返回的数据
    private LoginService.MyBinder myBinder = null;
    //更新数据的广播
    private MyReceiver receiver = null;
    //与服务的交互
    private ServiceConnection conn = new ServiceConnection() {

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            myBinder = (LoginService.MyBinder) service;
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //加载布局
        setContentView(R.layout.main_activity);
        //将页面添加进控制器
        MyApplication.getInstance().addActivity(this);
        //初始化组件
        init();
        //功能实现
        realize();
    }

    /**
     * 初始化组件
     */
    private void init() {
        gridview = (GridView) findViewById(R.id.gridview);
    }

    /**
     * 功能实现
     */
    private void realize() {
        getFunction();
        functionAdapter = new FunctionAdapter(this, functionList);
        gridview.setAdapter(functionAdapter);
        gridview.setOnItemClickListener(this);
        //长时间未响应服务
        intent = new Intent(MainActivity.this, LoginService.class);
        bindService(intent, conn, Service.BIND_AUTO_CREATE);
        //注册广播接收器
        receiver = new MyReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction("gg.com.toolbox.service.LoginService");
        MainActivity.this.registerReceiver(receiver, filter);
    }

    /**
     * 获取功能数据
     *
     * @return 是否添加成功
     */
    public void getFunction() {
        functionList = new ArrayList<>();
        HashMap<String, String> map = new HashMap<>();
        map.put("name", "账号信息");
        functionList.add(map);
        map = new HashMap<>();
        map.put("name", "功能开发中");
        functionList.add(map);
        map = new HashMap<>();
        map.put("name", "功能开发中");
        functionList.add(map);
        map = new HashMap<>();
        map.put("name", "功能开发中");
        functionList.add(map);
        map = new HashMap<>();
        map.put("name", "功能开发中");
        functionList.add(map);
    }

    /**
     * gridview点击事件
     *
     * @param parent
     * @param view
     * @param position
     * @param id
     */
    @SuppressLint("ShowToast")
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (position < 1) {
            intent = new Intent();
            intent.setClass(this, NotepadActivity.class);
            startActivity(intent);
        } else {
//            Toast.makeText(this,"功能开发中",1000).show();
        }
    }

    /**
     * 返回键不退出程序
     *
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            moveTaskToBack(false);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onResume() {
        super.onResume();
        AppConstant.time = DateUtils.getDateLong_yMdHms();
    }

    /**
     * 获取广播数据
     *
     * @author jiqinlin
     */
    public class MyReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            Bundle bundle = intent.getExtras();
            int type = bundle.getInt("type");
            switch (type) {
                //长时间未响应
                case 1:
                    if (isAppOnForeground()) {
                        Toast.makeText(MainActivity.this, "登录过期，请重新登录", 1000).show();
                        MyApplication.getInstance().closeActivity(MainActivity.this);
                        intent = new Intent(MainActivity.this, LoginActivity.class);
                        startActivity(intent);
                        finish();
                    } else {
                        //退出程序
                        MyApplication.getInstance().logout();
                    }
                    break;
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(conn);
        unregisterReceiver(receiver);
        //将页面从控制器中移除
        MyApplication.getInstance().deleteActivity(this);
    }

    /**
     * 在进程中去寻找当前APP的信息，判断是否在前台运行
     */
    private boolean isAppOnForeground() {
        ActivityManager activityManager = (ActivityManager) getApplicationContext()
                .getSystemService(Context.ACTIVITY_SERVICE);
        String packageName = getApplicationContext().getPackageName();
        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
        if (appProcesses == null)
            return false;
        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            if (appProcess.processName.equals(packageName)
                    && appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                return true;
            }
        }
        return false;
    }
}
